<?php

namespace App\Http\Controllers\WxApi\Traits;

use App\Models\WeChat;
use App\Models\WeChatKeyWord;
use Arr;
use Illuminate\Support\Facades\Log;

trait Reply
{
    protected function reply(string $content)
    {
        if ($rule = $this->getRule($content)) {

            switch ($rule->type) {
                case 'text':
                    //随机返回消息列队中的一个
                    return $this->message->text(Arr::random($rule->text->contents));

                case 'news':
                    return $this->message->news($rule->news->contents);
                default :
                    //模块处理
                    if ($rule->module) {
                        $class = 'Modules\\' . $rule['module'] . '\System\Processor';
                       return app($class)->handle($rule, $this->message,$this->model);
                    }
            }
        }
    }

    protected function getRule(string $content)
    {


        //simplexml_load_string解析xml后结构是一个object对象，所以不能用全等

        $keywords = WeChatKeyWord::site()->get();

        //完整匹配 优先
        foreach ($keywords as $keyword) {
            if ($keyword->word == $content) {
                //关键词唯一
                return $keyword->rule;
            }
        }
        //模糊匹配
        foreach ($keywords as $keyword) {
            if ($keyword->regexp && preg_match("/{$keyword->word}/i", $content)) {
                return $keyword->rule;
            }
        }

    }
}
